package com.library.repository;

import com.library.entity.Reservation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 预约数据访问层接口
 */
@Repository
public interface ReservationRepository extends JpaRepository<Reservation, Long> {
    /**
     * 根据用户ID查找预约列表
     */
    @Query("SELECT r FROM Reservation r JOIN FETCH r.book JOIN FETCH r.user " +
           "WHERE r.user.id = :userId ORDER BY r.createdAt DESC")
    List<Reservation> findByUserIdOrderByCreatedAtDesc(@Param("userId") Long userId);

    /**
     * 根据图书ID查找预约列表
     */
    @Query("SELECT r FROM Reservation r JOIN FETCH r.book JOIN FETCH r.user " +
           "WHERE r.book.id = :bookId ORDER BY r.createdAt ASC")
    List<Reservation> findByBookIdOrderByCreatedAtAsc(@Param("bookId") Long bookId);

    /**
     * 根据用户ID和图书ID查找预约
     */
    @Query("SELECT r FROM Reservation r JOIN FETCH r.book JOIN FETCH r.user " +
           "WHERE r.user.id = :userId AND r.book.id = :bookId")
    Optional<Reservation> findByUserIdAndBookId(@Param("userId") Long userId, @Param("bookId") Long bookId);

    /**
     * 根据状态查找预约列表
     */
    @Query("SELECT r FROM Reservation r JOIN FETCH r.book JOIN FETCH r.user " +
           "WHERE r.status = :status ORDER BY r.createdAt ASC")
    List<Reservation> findByStatusOrderByCreatedAtAsc(@Param("status") String status);

    /**
     * 根据用户ID和状态查找预约列表
     */
    @Query("SELECT r FROM Reservation r JOIN FETCH r.book JOIN FETCH r.user " +
           "WHERE r.user.id = :userId AND r.status = :status ORDER BY r.createdAt DESC")
    List<Reservation> findByUserIdAndStatusOrderByCreatedAtDesc(@Param("userId") Long userId, @Param("status") String status);

    /**
     * 根据用户ID删除其所有预约
     *
     * @param userId 用户ID
     */
    void deleteByUserId(Long userId);
}

